package com.loongtech.bi.manager.system;

import com.loongtech.bi.action.system.SysLogAction.SysLogBean;
import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.system.EntitySysFunction;
import com.loongtech.bi.entity.system.EntitySystemLog;
import com.loongtech.core.jpa.manager.ManagerBase;
import com.loongtech.core.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.loongtech.bi.manager.system.SysProjectManager.projectIdNameMap;

@Service("sysLogManager")
public class SysLogManager extends ManagerBase<EntitySystemLog> {
	private static final long serialVersionUID = 5134272747892532556L;
    @Resource
    private SysFunctionManager sysFunctionManager;
	/**
	 * 增加日志
	 * 
	 * @param operator
	 * @param action
	 * @return
	 */
	public boolean addLog(String operator, String action) {
		if (null == operator || null == action) {
			return false;
		}
		EntitySystemLog entity = new EntitySystemLog();
		entity.setOperator(operator);
		entity.setAction(action);
		persist(entity);
		return true;
	}

	public void removePassed() {
		java.util.Calendar calender = Calendar.getInstance();
		calender.setTime(new java.util.Date(System.currentTimeMillis()));
		calender.set(Calendar.MONTH, calender.get(Calendar.MONTH) - 1);
		executeUpdate("delete from EntityLog as u where u.operTime<?", calender.getTime());
	}

	public List<EntitySystemLog> search(SysLogBean input) {
		String operator = input.getOperator();
		Date startDate = input.getStartTime();
		Date endDate = input.getTime();
		String keyword = input.getKeyword();
		
		// operator
		List<EntitySystemLog> list = null;
		if (!StringUtils.isEmpty(operator)) {
			list = findByQuery("from EntitySystemLog where operator=:operator and operTime>=:startTime and operTime<=:endTime order by operTime desc", "operator", operator, "startTime", startDate, "endTime", endDate);
		} else {
			list = findByQuery("from EntitySystemLog where operTime>=:startTime and operTime<=:endTime order by operTime desc", "startTime", startDate, "endTime", endDate);
		}
		if (!StringUtils.isEmpty(keyword) && list != null && list.size() > 0) {
			List<EntitySystemLog> tmp = new ArrayList<>();
			
			for (EntitySystemLog e: list) {
				if (e.getAction() != null && e.getAction().contains(keyword)) {
					tmp.add(e);
				}
			}
			if (tmp.size() > 0) {
				list = tmp;
			}
		}
		
		return list;
	}

	//springmvc 查询
    public Page<List<EntitySystemLog>> queryByPage( Integer curPage, Integer pageSize, Date dateStart, Date dateEnd, String operator, String gameId, String page) {
        List<Object> param = new ArrayList<>();
        StringBuilder hql = new StringBuilder(" from EntitySystemLog e where 1=1 ");

        if (!Utils.isEmptyStr(operator)) {
            hql.append(" and e.operator like ?");
            param.add("%" + operator + "%");
        }
        if (!Utils.isEmptyStr(gameId)) {
            hql.append(" and e.gameId = ?");
            param.add(gameId);
        }
        if (!Utils.isEmptyStr(page)) {
            hql.append(" and e.action like ?");
            param.add("%" + page + "%");
        }
        hql.append("and operTime >= ? and operTime <= ? order by operTime desc");
        param.add(dateStart);
        param.add(dateEnd);
        Integer totalSize = countNum(hql.toString(), param.toArray());
        //数据
        List<EntitySystemLog> list = findByQuery((curPage - 1) * pageSize, pageSize, hql.toString(), param.toArray());
        for (EntitySystemLog entitySystemLog : list) {
            String gameid = entitySystemLog.getGameId();
            entitySystemLog.setGameName(projectIdNameMap.get(gameid));

            String action = entitySystemLog.getAction();
            EntitySysFunction res = sysFunctionManager.get(Integer.parseInt(action));
            entitySystemLog.setActionName(res.getName());
        }
        return new Page<>(list, totalSize, curPage, pageSize);
    }

    public List<EntitySystemLog> search(String operator, Date date) {
		// 限制时间, 最多查询一个月的日志
		java.util.Calendar calender = Calendar.getInstance();
		calender.setTime(new java.util.Date(System.currentTimeMillis()));
		calender.set(Calendar.MONTH, calender.get(Calendar.MONTH) - 1);
		if (null == date || date.getTime() <= calender.getTimeInMillis()) {
			date = calender.getTime();
		}

		// operator
		List<Object> list = null;
		if (null != operator && !operator.isEmpty()) {
			list = findByQuery(
					"select u from EntitySystemLog as u where u.operator=:operator and u.operTime>:operTime order by operTime desc", "operator", operator, "operTime", date);
		} else {
			list = findByQuery("select u from EntitySystemLog as u where u.operTime>? order by operTime desc", date);
		}

		// 类型转换
		List<EntitySystemLog> retList = new ArrayList<EntitySystemLog>();
		if (null != list && !list.isEmpty()) {
			for (Object o : list) {
				retList.add((EntitySystemLog) o);
			}
		}
		return retList;
	}
}